package com.wtwd.campus.receiver;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.annotation.MsgType;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.dao.CommandRecordMapper;
import com.wtwd.campus.dao.DeviceInfoMapper;
import com.wtwd.campus.dao.WhiteListMapper;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.h5_manager.entity.DeviceLog;
import com.wtwd.campus.h5_manager.service.DeviceLogService;
import com.wtwd.campus.utils.PushUtils;
import com.wtwd.campus.utils.ReceiverUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * @author mjy
 * @date 2021/06/30
 * @description
 */
@Service
@MsgType(value = Constants.SINGLE_WHITELIST_NUMBER)
public class ReceiveWhiteCallHandler implements IReceiverHandler {

    @Autowired
    private DeviceInfoMapper deviceInfoMapper;
    @Autowired
    private CommandRecordMapper commandRecordMapper;
    @Autowired
    private WhiteListMapper whiteListMapper;
    @Autowired
    private ReceiverUtils receiverUtils;
    @Autowired
    private PushUtils pushUtils;
    @Autowired
    private DeviceLogService deviceLogService;
    @Override
    public void handlerMessage(MqMessage mqMessage) {
        MqSingleWhiteCallResult mqSingleWhiteCallResult = (MqSingleWhiteCallResult) mqMessage.getObject();
        DeviceInfo deviceInfo = deviceInfoMapper.getDeviceInfoByImei(mqSingleWhiteCallResult.getImei());
        String name = mqSingleWhiteCallResult.getName();
        String phone = mqSingleWhiteCallResult.getPhone();
        String imei = mqSingleWhiteCallResult.getImei();
        Integer sequence = mqSingleWhiteCallResult.getSequence();
        String commandNumber = mqSingleWhiteCallResult.getCommandNumber();
        //找不到该设备不处理
        if (deviceInfo != null) {
            ArrayList<String> commandTypeList = new ArrayList<>();
            commandTypeList.add(Constants.DEL_WHITE_CALL);
            commandTypeList.add(Constants.SINGLE_WHITELIST_NUMBER);
            commandTypeList.add(Constants.UPDATE_WHITE_CALL);
            //根据课程表和imei号找到唯一的一条指令记录,和命令类型
            CommandRecord commandRecord = commandRecordMapper.getCommandRecordByCondition(mqSingleWhiteCallResult.getImei(), mqSingleWhiteCallResult.getSequence(), commandTypeList,commandNumber);
            if (commandRecord == null) {
                return;
            }
            // 所有发送出去的指令都会在command_record表中存在，如果没找到，就不处理。
            if (commandRecord.getCommandNumber().equals(commandNumber)) {
                //删除
                if (commandRecord.getCommandType().equals(Constants.DEL_WHITE_CALL)) {
                    whiteListMapper.delWhiteCall(deviceInfo.getDeviceId(), sequence);
                }
                //修改 或 添加
                else {
                    // 判断在该位置是否有数据，防止连续存了两条指令（先删除后修改）
                    addOrUpdateWhiteCall(deviceInfo.getDeviceId(),sequence,imei,name,phone,commandNumber);
                }
                //完善指令发送状态
                commandRecordMapper.completeCommand(commandRecord.getId(), System.currentTimeMillis());
                //有定位数据才处理
                LocationDataVo locationDataVo = null;
                if (mqSingleWhiteCallResult.getMqLocationData() != null) {
                    if (mqSingleWhiteCallResult.getMqLocationData().getLatitude() != 0 && mqSingleWhiteCallResult.getMqLocationData().getLongitude() != 0) {
                        //进行定位数据存储以及围栏告警记录的存储
                        //处理指令回复的时间
                        String deviceDate = mqSingleWhiteCallResult.getDeviceDate();
                        String deviceTime = mqSingleWhiteCallResult.getDeviceTime();
                        Long time = getTime(deviceDate, deviceTime);
                        deviceInfo = receiverUtils.dealLocation(mqSingleWhiteCallResult.getMqLocationData(), time, deviceInfo,1);
                        locationDataVo = new LocationDataVo();
                        locationDataVo.setLocationType(1);
                        locationDataVo.setLatitude(mqSingleWhiteCallResult.getMqLocationData().getLatitude().toString());
                        locationDataVo.setLongitude(mqSingleWhiteCallResult.getMqLocationData().getLongitude().toString());
                        locationDataVo.setAddress(deviceInfo.getAddress());
                        locationDataVo.setImei(imei);
                        locationDataVo.setLocationTime(time);
                    }
                }
                //更新设备最后上传时间
                deviceInfo.setLastUpTime(System.currentTimeMillis());
                deviceInfoMapper.updateDeviceInfo(deviceInfo);
                //删除缓存中的指令
                String delKey = Constants.SINGLE_WHITELIST_NUMBER.concat("-").concat(mqSingleWhiteCallResult.getCommandNumber().concat("-").concat(String.valueOf(mqSingleWhiteCallResult.getSequence())));
                receiverUtils.deleteCommandInRedis(mqSingleWhiteCallResult.getImei(), delKey);
            }
            //存储设备接收日志
            DeviceLog deviceLog = new DeviceLog();
            deviceLog.setSendUser(Constants.DEVICE_USER);
            deviceLog.setImei(imei);
            deviceLog.setBigType(Constants.MESS_TYPE);
            deviceLog.setType(Constants.SINGLE_WHITELIST_NUMBER);
            JSONObject contant = new JSONObject();
            contant.put("设备号", imei);
            contant.put("白名单序号",sequence);
            contant.put("白名单号码",phone);
            contant.put("白名单名称", mqSingleWhiteCallResult.getName());
            contant.put("指令回复时间 时分秒",mqSingleWhiteCallResult.getDeviceTime());
            contant.put("日期",mqSingleWhiteCallResult.getDeviceDate());
            contant.put("经度", mqSingleWhiteCallResult.getMqLocationData().getLongitude());
            contant.put("纬度", mqSingleWhiteCallResult.getMqLocationData().getLatitude());
            contant.put("速度", mqSingleWhiteCallResult.getMqLocationData().getSpeed());
            contant.put("方位角", mqSingleWhiteCallResult.getMqLocationData().getOrientation());
            deviceLog.setCmd(contant.toJSONString());
            deviceLog.setSendTime(System.currentTimeMillis());
            deviceLog.setCommandNumber(commandNumber);
            deviceLog.setState(1);
            deviceLogService.addDeviceLog(deviceLog);
        } else {
            saveUnInStorage(imei);
            receiverUtils.cloaseChannel(imei);
        }
    }

    public void addOrUpdateWhiteCall(Integer deviceId,Integer sequence,String imei,String name,String phone,String commandNumber){
        DeviceWhiteList deviceWhiteList = whiteListMapper.getDeviceWhiteListByDeviceIdAndSequence(deviceId,sequence);
        if(deviceWhiteList == null){
            DeviceWhiteCall deviceWhiteCall = new DeviceWhiteCall();
            deviceWhiteCall.setDeviceId(deviceId);
            deviceWhiteCall.setImei(imei);
            deviceWhiteCall.setName(name);
            deviceWhiteCall.setPhone(phone);
            deviceWhiteCall.setSequence(sequence);
            deviceWhiteCall.setStatus(Constants.CLASSES_PATTERN_NORMAl);
            deviceWhiteCall.setCommandNumber(commandNumber);
            whiteListMapper.addDeviceWhiteCall(deviceWhiteCall);
        }else{
            if(commandNumber.equalsIgnoreCase(deviceWhiteList.getCommandNumber())){
                commandNumber = null;
            }
            whiteListMapper.updateDeviceWhiteCall(deviceId,sequence,name,phone,commandNumber,Constants.CLASSES_PATTERN_NORMAl);
        }
    }
}
